/**
 * 
 */
package com.kedacom.cometd.javaclient;

import java.util.HashMap;
import java.util.Map;

import org.cometd.bayeux.Message;
import org.cometd.bayeux.client.ClientSessionChannel;
import org.cometd.client.BayeuxClient;
import org.cometd.client.transport.ClientTransport;
import org.cometd.client.transport.LongPollingTransport;
import org.eclipse.jetty.client.HttpClient;

/**
 * (用一句话描述类的主要功能)
 * @author huangchunhua
 * @date 2013-12-24
 */

public class CometdJavaCilent {

	public static void main(String[] swgs) throws Exception {
		// Create (and eventually set up) Jetty's HttpClient:
		HttpClient httpClient = new HttpClient();
		// Here set up Jetty's HttpClient, for example:
		// httpClient.setMaxConnectionsPerAddress(2);
		httpClient.start();

		// Prepare the transport
		Map<String, Object> options = new HashMap<String, Object>();
		ClientTransport transport = LongPollingTransport.create(options, httpClient);

		BayeuxClient client = new BayeuxClient("http://172.16.80.120:8088/cometd/cometd", transport);
		// Here set up the BayeuxClient, for example:
		// client.getChannel(Channel.META_CONNECT).addListener(new
		// ClientSessionChannel.MessageListener() { ... });
		client.handshake();

		client.handshake();
		boolean handshaken = client.waitFor(1000, BayeuxClient.State.CONNECTED);
		if (handshaken) {
			// Here handshake is successful
		}

		Map<String, Object> data = new HashMap<String, Object>();
		// Fill in the data
		// data.put("type", "notify");
		// data.put("message", "2222222222");

		data.put("type", "notify");
		data.put("message", "slslslsl");
		data.put("receivers", "test1,test2");

		// "room":"/chat/demo","user":"222232323","chat":"4444444","peer":"aaa"

		client.getChannel("/notify/system").publish(data, new ClientSessionChannel.MessageListener() {

			@Override
			public void onMessage(ClientSessionChannel channel, Message message) {
				if (message.isSuccessful()) {

					System.out.println("3333333333333");
				} else {
					System.out.println("4444444444444444");
				}
			}
		});
		System.out.println("end");

	}
}
